package com.chhuang.utils.string;

import java.util.Random;

/**
* 生成4-32位的随机密码
* @author 张喻洁
* @date Dec 19, 2012 12:15:09 PM
*
*/
public class PwdUtils {
	private static Random r = new Random();
	private static char[] letter = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
			'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
			'v', 'w', 'x', 'y', 'z' };
	private static int letterArrayLen = letter.length;
	private static char[] number = { '0', '1', '2', '3', '4', '5', '6', '7',
			'8', '9' };
	private static int numberArrayLen = number.length;
	private static int minPwdLen = 4;
	private static int maxPwdLen = 32;

	/**
	 * 字母密码，建议10位以上
	 * 
	 * @param length
	 * @return String
	 */
	public static String generateLetterPwd(int length) {
		length = format(length);
		char[] pwd = new char[length];
		for (int i = 0; i < length; i++) {
			char current = randomLetter();
			pwd[i] = current;
		}
		return String.valueOf(pwd);
	}

	private static char randomLetter() {
		int random = Math.abs(r.nextInt());
		int index = random % letterArrayLen;
		char current = letter[index];
		return current;
	}

	/**
	 * 数字密码，建议12位以上
	 * 
	 * @param length
	 * @return String
	 */
	public static String generateNumberPwd(int length) {
		length = format(length);
		char[] pwd = new char[length];
		for (int i = 0; i < length; i++) {
			char current = randomNumber();
			pwd[i] = current;
		}
		return String.valueOf(pwd);
	}

	private static char randomNumber() {
		int random = Math.abs(r.nextInt());
		int index = random % numberArrayLen;
		char current = number[index];
		return current;
	}

	/**
	 * 字母数字组合密码，建议10位以上
	 * 
	 * @param length
	 * @return String
	 */
	public static String generateComplexPwd(int length) {
		length = format(length);
		char[] pwd = new char[length];
		for (int i = 0; i < length; i++) {
			char current;
			int random = Math.abs(r.nextInt()) % 2;
			if (random == 0) {
				current = randomNumber();
			} else {
				current = randomLetter();
			}
			pwd[i] = current;
		}
		return String.valueOf(pwd);
	}
	
	public static String generateComplexPwdDefault() {
		return generateComplexPwd(20);
	}

	private static int format(int length) {
		if (length < minPwdLen) {
			length = minPwdLen;
		}
		if (length > maxPwdLen) {
			length = maxPwdLen;
		}
		return length;
	}
}
